home *** CD-ROM | disk | FTP | other *** search
- Path: gate.net!pslfl2-25
- From: bhutto@gate.net (William Hutto)
- Newsgroups: comp.lang.c
- Subject: Re: Splitting String ?
- Date: 12 Jan 1996 23:24:04 GMT
- Organization: CyberGate, Inc.
- Message-ID: <4d6qik$r78@news.gate.net>
- References: <HAKOLA.96Jan12151128@jung.hut.fi>
- NNTP-Posting-Host: pslfl2-36.gate.net
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- In article <HAKOLA.96Jan12151128@jung.hut.fi>,
- hakola@cadmail.hut.fi (Petri Hakola) wrote:
- >
- > Have I missed something (again:) or why doesn't this code
- > work? I should split dos-a-like-filename and add new postfix
- > instead of old one (i.e. DATA.TXT --> DATA.UPD It seems to
- > work correctly if the filename has an old postfix, but if
- > there isn't one start won't return what it should.
- >
- > - P -
- >
- >
- >---Clip---
- >#include <stdio.h>
- >#include <string.h>
- >
- >char *newname(char *s) {
-
- If you're going to be passing pointers to string literals to this function or
- if you don't know that you can legally address chars beyond the end of the
- string it should be defined taking an argument of const char * (for your own
- protection).
-
- >
- > char *dot;
- > char *start;
-
- Make start a static array, which will allow you to copy the const char *s to
- it for manipulation. Static so that it sticks around after you return to the
- caller.
-
- > char end[5];
- >
- > strcpy(end,".UPD");
-
- If end is always gonna be equal to ".UPD" you can make it static to save you
- the initialization code each time the function is called.
-
- > start = s;
-
- Copy s to start and then work with start which will be oversized to allow
- appending chars.
-
- > dot = strchr(s,'.');
- > if( dot == NULL) {
- > start[strlen(start)] = '\0';
- > dot = end;
-
- The above to lines are not needed at all.
-
- > } else {
- > *dot = '\0';
- > dot++;
- > dot = end;
-
- Here, you increment dot and then assign it a different value. These two lines
- are unnecessary also.
-
- > }
- > strcat(start, dot);
-
- Here, you only need to append end to start.
-
- > return start;
- >}
- >
- >main() {
- > printf("%s\n",newname("LONGNAME.TXT"));
-
- Here, your code worked because you replaced 3 letters with 3 letters. Even
- though your system might allow it, it's illegal, and certainly not portable to
- change a string literal.
-
- > printf("%s\n",newname("NOEND"));
-
- With this one, where is it going to put ".UPD"?
-
- >}
-
- char *newname(const char *s)
- {
-
- char *dot;
- static char start[MAX_FILENAME_SIZE];
- static const char *end = ".UPD";
-
- strcpy(start,s); /*copy s to start before any manipulation*/
- dot = strrchr(start,'.'); /*reverse in case multiple '.'s in future*/
- if(dot)
- *dot = '\0';
- strcat(start,end);
- return start;
- }
-
- Bill
-
- "Whatcha got on?...Your mind?"
-